import pathlib
import time
import re
import typing
import os
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *





def print_with_time(*args, **kwargs):
    """在输出内容前添加当前时间戳，使用rich.print进行格式化输出
    
    功能：在所有输出内容前自动添加当前本地时间，时间格式为YYYY-MM-DD HH:MM:SS
    时间会以蓝色加粗样式显示，其余内容保持rich的默认格式化特性
    
    Args:
        *args: 任意数量的位置参数，将被原样传递给rich.print
        **kwargs: 任意关键字参数，将被原样传递给rich.print
    
    Example:
        >>> print_with_time("系统启动完成")
        [bold blue][2025-08-07 16:45:30][/bold blue] 系统启动完成
        
        >>> print_with_time("操作结果：", "[green]成功[/green]")
        [bold blue][2025-08-07 16:46:10][/bold blue] 操作结果：[green]成功[/green]
    """
    # 获取当前时间并格式化为字符串
    current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    # 拼接时间前缀与输出内容并打印
    rich.print(f"[bold blue][{current_time}][/bold blue]", *args, **kwargs)






def On_SelectPage_Select_FirstCategory(driver:WebDriver,Cate_Name:str):
    """选择第一个类目

    Args:
        driver (WebDriver): WebDriver 实例
        Cate_Name (str): 类目名称
    """
        # 确保开启 [选择类目] 的容器
    try:
        
        WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='热门推荐']")))
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='选择类目']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        pass

    # 选择第一级类目
    try:
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='{Cate_Name}']")))

        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        try:
            WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[text()='T恤']")))
        except TimeoutException:
            print_with_time(f"提示 : 选择一级类目失败!没有出现二级类目菜单!请检查!")
        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [{Cate_Name}] 元素!")
        




def On_SelectPage_Select_SecondCategory(driver:WebDriver,Cate_Name:str):
    """选择第二个类目

    Args:
        driver (WebDriver): WebDriver 实例
        Cate_Name (str): 类目名称
    """
    try:
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//ul/li[contains(@class,'cate') and @title='{Cate_Name}']//*[text()='{Cate_Name}']")))
        driver.execute_script("arguments[0].scrollIntoView({block: 'center', inline: 'center'});",element)
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
        
        try:
            WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//button[not(@disabled)]//*[text()='确认，下一步'] | //div[contains(@class,'catProp')]")))
        except TimeoutException:
            print_with_time(f"提示 : 选择二级类目失败!当前无法点击 [下一步] 按钮!请检查!")

        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [{Cate_Name}] 元素!")



def On_SelectPage_Select_CatePro(driver:WebDriver,CatePro:str):
    """在类目选择页面中选择品牌

    Args:
        driver (WebDriver): WebDriver 实例
        Cate_Name (str): 品牌名称
    """
    # 检测是否有 [品牌] 相关锚点的元素.如果不存在,可以直接跳过.
    
    
    
    # 判断是否有 [品牌] 相关锚点的元素.
    try:
        WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'catProp')]")))
    except TimeoutException:
        print_with_time(f"提示 : 没有探测到当前页面有关于 [品牌] 选择的元素!当前类目不需要添加品牌信息,可以直接跳过!")
        return
    
    # 找到触发 [品牌] 选择按钮的元素
    try:
        element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[contains(@class,'catProp')]//input")))
        element.click()
        
        # 输入 [品牌名称]
        try:
            element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//*[@class='sell-o-select-options']//input")))
            element.send_keys(CatePro)
            
            # 判断是否输入了指定的 [品牌] 名称
            try:
                WebDriverWait(driver=driver,timeout=1).until(expected_conditions.text_to_be_present_in_element_value((By.XPATH,f"//*[@class='sell-o-select-options']//input"),CatePro))
                
                try:
                    element = WebDriverWait(driver=driver,timeout=1).until(expected_conditions.presence_of_element_located((By.XPATH,f"//div[@title='{CatePro}']//div[text()='{CatePro}']")))
                    element.click()
                except TimeoutException:
                    print_with_time(f"提示 : 没有找到 {CatePro} 对应的品牌名!")
                
                
            except TimeoutException:
                print_with_time(f"提示 : 输入的分类名{CatePro}没有出现!")
            
            
        except TimeoutException:
            print_with_time(f"提示 : 品牌输入框没有找到!")
        
    except TimeoutException:
        print_with_time(f"提示 : 没有找到触发 [品牌] 输入框的元素!")
        



def Goto_Parameter_Input(driver:WebDriver,Delay:float=5):
    """进入到参数填写页面.

    Args:
        driver (WebDriver): WebDriver 实例
        Delay (float, optional): 函数延时参数. Defaults to 5.
    """
    try:
        element = WebDriverWait(driver=driver,timeout=5).until(expected_conditions.presence_of_element_located((By.XPATH,f"//button[not(@disabled)]//*[text()='确认，下一步']")))
        try:
            element.click()
        except (ElementClickInterceptedException,ElementNotInteractableException):
            driver.execute_script("arguments[0].click();",element)
    except TimeoutException:
        print_with_time(f"提示 : 没有找到 [下一步] 按钮,无法进入参数填写页面!")
    finally:
        time.sleep(Delay)




if __name__ == "__main__":
    options = Options()
    options.add_experimental_option("debuggerAddress", "127.0.0.1:9652")
    service = Service()
    driver = WebDriver(options=options, service=service)
    debug_json_data = requests.get(
        url="http://127.0.0.1:9652/json", timeout=5).json()

    # 判断获取回来的数据是否正确
    if not isinstance(debug_json_data, list):
        print_with_time("接口返回数据格式不正确（非列表或为空）")
        exit(0)

    # 过来掉不需要的 page 页面
    filter_json_data = list(
                                    filter(lambda item: (
                                        item['type'] == "page" and
                                        not item['title'].lower().startswith("devtools") and
                                        not item['title'].lower().startswith("offscreen") and
                                        not item['title'].lower().startswith("新标签页") and
                                        not item['url'].lower().startswith("edge://newtab/") and
                                        not item['url'].lower().startswith("chrome-extension") and
                                        not item['url'].lower().startswith("chrome-devtools")
                                    ), debug_json_data)
                                )
    current_activate_handle = filter_json_data[0]['id']
    driver.switch_to.window(current_activate_handle)